package com.milling.common.utils.scanner;

import java.net.Socket;
import java.io.InputStream;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicBoolean;

public class SocketListener implements Runnable {
    private final Socket socket;
    private final AtomicBoolean isRunning;
    private final MessageCallback callback; // 消息回调接口

    // 构造函数
    public SocketListener(Socket socket, MessageCallback callback) {
        this.socket = socket;
        this.callback = callback;
        this.isRunning = new AtomicBoolean(true);
    }

    // 监听线程主逻辑
    @Override
    public void run() {
        try (InputStream in = socket.getInputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;

            while (isRunning.get() && !socket.isClosed()) {
                bytesRead = in.read(buffer); // 阻塞读取数据
                if (bytesRead == -1) {
                    // 连接已关闭
                    callback.onConnectionClosed();
                    break;
                }

                // 处理接收到的数据
                String message = new String(buffer, 0, bytesRead, "UTF-8");
                callback.onMessageReceived(message);
            }
        } catch (IOException e) {
            if (!socket.isClosed()) {
                callback.onError("Socket error: " + e.getMessage());
            }
        } finally {
            stopListening(); // 确保资源清理
        }
    }

    // 停止监听
    public void stopListening() {
        isRunning.set(false);
        try {
            if (!socket.isClosed()) {
                socket.close();
            }
        } catch (IOException e) {
            System.err.println("Error closing socket: " + e.getMessage());
        }
    }

    // 消息回调接口
    public interface MessageCallback {
        void onMessageReceived(String message);
        void onConnectionClosed();
        void onError(String errorMsg);
    }
}
